package com.dianjing.dianqun.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dianjing.dianqun.common.base.BaseRestController;
import com.dianjing.dianqun.model.DianQunUser;
import com.dianjing.dianqun.utils.UserUtils;

/**
 * @date : 2017年10月9日
 * 
 * @author: baoyongtao
 * 
 * @see :
 * 
 */
@Controller
public class LoginController extends BaseRestController {

//	@RequestMapping({"/index","/","/favicon.ico"})
	@RequestMapping({"/index","/"})
	public String index(HttpServletRequest request,Model model) {
		model.addAttribute("user", UserUtils.getUser());
		return "system/index";
	}

	@RequestMapping("/login")
	public String login() {
		Subject subject = SecurityUtils.getSubject();
		// 如果已经登录，则跳转到管理首页
		if (subject.isAuthenticated()) {
			return "redirect:/index";
		}
		return "login";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model) {
		Subject subject = SecurityUtils.getSubject();
		// 如果已经登录，则跳转到管理首页
		if (subject != null) {
			subject.logout();
		}
		return "redirect:/login";
	}

	@PostMapping(value = "/login")
	public String login(DianQunUser currUser, Model model) {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			return "redirect:/index";
		}
		UsernamePasswordToken token = new UsernamePasswordToken(currUser.getUsername(), currUser.getPassword());
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			token.clear();
			model.addAttribute("message", "账号密码错误");
			model.addAttribute("user", currUser);
			return "login";
		}
		return "redirect:/index";
	}
}
